<?php

namespace app\beautiful\controller\admin\project;

use app\BaseController;

use app\common\logic\DataLogic;

use app\beautiful\logic\LogsLogic;

use app\beautiful\logic\printer\PrinterLogic;

use app\beautiful\model\logs\ApplyLogsModel;

use app\beautiful\model\logs\ProjectWriteOffModel;

use app\beautiful\model\member\MemberModel;

use app\beautiful\model\member\MemberOnceCardItemModel;

use app\beautiful\model\member\MemberOnceCardModel;

use app\beautiful\model\member\MemberProjectModel;

use think\facade\Db;



class OncecardOrder extends BaseController{

    protected $name='次卡订单';



    public function index()

    {

        $today=date("Y-m-d",$this->request->time());

        $member_once_card_id=$this->request->param('member_once_card_id/d',0);

        $mobile=$this->request->param('mobile');

        $status=$this->request->param('status/d',1);

        $where=[

            ['shop_id','=',$this->request->shopId],

        ];

        if(!empty($member_once_card_id)) $where[]=['member_once_card_id','=',$member_once_card_id];



        if(!empty($mobile)){

            $member_ids=MemberModel::where([

                ['shop_id','=',$this->request->shopId],

                ['mobile','=',$mobile]

            ])->column('member_id') ?? [];

            $where[]=['member_id','in',$member_ids];

        }

        if(!in_array($status,[1,2,3])) $where[]=['status','=',-1];

        if($status==1) $where[]=['status','=',1];

        if($status==1) $where[]=['valid_end_time','>=',$today];

        if($status==2) $where[]=['status','=',8];

        if($status==3) $where[]=['status','=',1];

        if($status==3) $where[]=['valid_end_time','<',$today];



        $member_once_card_model=new MemberOnceCardModel();

        $member_once_card_model=$member_once_card_model->with(['member']);

        $order=['add_time'=>'desc'];

        $field="*";

        $append=['add_time_format','status_means'];

        $return=DataLogic::getDataList($member_once_card_model,$where,$order,$field,$this->request->limit,$this->request->page,$append);

        return $this->success($return);

    }



    public function getMemberOnceCardList()

    {

        $member_id=$this->request->param('member_id/d',0);

        $where=[

            ['shop_id','=',$this->request->shopId],

            ['member_id','=',$member_id]

        ];



        $member_once_card_model=new MemberOnceCardModel();

        $member_once_card_model=$member_once_card_model->with(['items']);

        $order=['add_time'=>'desc'];

        $field="*";

        $append=['add_time_format','status_means','pay_type_mean','pay_time_format','status_another'];

        $return=DataLogic::getDataList($member_once_card_model,$where,$order,$field,$this->request->limit,$this->request->page,$append);

        return $this->success($return);

    }



    public function detail()

    {

        $member_once_card_id=$this->request->param('member_once_card_id/d',0);

        if($member_once_card_id ==0) return $this->error($this->name.'不存在');

        if(null === $member_once_card = MemberOnceCardModel::find($member_once_card_id)) return $this->error($this->name.'不存在');

        if($member_once_card->shop_id != $this->request->shopId) return $this->error($this->name.'不存在');



        if(null === $member = MemberModel::find($member_once_card->member_id)) return $this->error($this->name.'不存在');

        if($member->shop_id != $this->request->shopId) return $this->error($this->name.'不存在');



        $items=MemberOnceCardItemModel::where([

            ['shop_id','=',$this->request->shopId],

            ['member_id','=',$member->member_id],

            ['member_once_card_id','=',$member_once_card_id]

        ])->select()->toArray();

        if(empty($items)) return $this->error('次卡错误');





        $detail=[

            'member_once_card_id'=>$member_once_card_id,

            'name'=>$member_once_card->name,

            'add_time_format'=>$member_once_card->add_time_format,

            'valid_end_time'=>$member_once_card->valid_end_time,

            'status'=>$member_once_card->status,

            'status_another'=>$member_once_card->status_another,

            'status_means'=>$member_once_card->status_means,

            'need_pay'=>$member_once_card->need_pay,

            'pay_type_mean'=>$member_once_card->pay_type_mean,

            'pay_time_format'=>$member_once_card->pay_time_format,

            'total_price'=>$member_once_card->total_price,

            'coupon_money'=>$member_once_card->coupon_money,

            'integral_balance'=>$member_once_card->integral_balance,

            'member_name'=>$member->nick_name,

            'member_mobile'=>$member->mobile,

            'items'=>$items

        ];



        return $this->success(['detail'=>$detail]);

    }



    public function writeOff()

    {

        $today=date("Y-m-d",$this->request->time());

        $member_once_card_item_id=$this->request->param('member_once_card_item_id/d',0);

        $num=$this->request->param('num/d',0);

        $remark=$this->request->param('remark');



        if($num <= 0) return $this->error('核销次数不能小于0');



        if($member_once_card_item_id ==0) return $this->error($this->name.'不存在');

        if(null === $member_once_card_item = MemberOnceCardItemModel::find($member_once_card_item_id)) return $this->error($this->name.'不存在');

        if($member_once_card_item->shop_id != $this->request->shopId) return $this->error($this->name.'不存在');



        if(null === $member_once_card = MemberOnceCardModel::find($member_once_card_item->member_once_card_id)) return $this->error($this->name.'不存在');

        if($member_once_card->status != 1) return $this->error($this->name.'的状态不在待消费');

        if($member_once_card->valid_end_time < $today) return $this->error($this->name.'已过期');



        if(null === $member_project = MemberProjectModel::where([

                ['member_id','=',$member_once_card_item->member_id],

                ['source','=','once_card'],

                ['project_id','=',$member_once_card_item->project_id],

                ['member_once_card_item_id','=',$member_once_card_item_id],

                ['total_num','=',$member_once_card_item->total_num],

                ['remain_num','=',$member_once_card_item->remain_num]

            ])->find()){

            return $this->error($this->name.'不存在');

        }



        if(null === $member = MemberModel::find($member_once_card->member_id)) return $this->error($this->name.'不存在');

        if($member->shop_id != $this->request->shopId) return $this->error($this->name.'不存在');



        $remain_num=$member_once_card_item->remain_num - $num;

        if($remain_num < 0) return $this->error($this->name.'的剩余数量不够这次核销');

        Db::startTrans();

        try{

            //处理我的次卡项目

            $member_once_card_item->remain_num = $remain_num;

            $member_once_card_item->save();



            //处理次卡状态

            if(null === MemberOnceCardItemModel::where([

                    ['shop_id','=',$this->request->shopId],

                    ['member_id','=',$member->member_id],

                    ['member_once_card_id','=',$member_once_card->member_once_card_id],

                    ['remain_num','>',0]

                ])->find()){

                $member_once_card->status=8;

                $member_once_card->save();

            }

            //处理我的项目

            $member_project->remain_num = $remain_num;

            $member_project->save();



            //添加核销记录

            $res=LogsLogic::project($this->request->shopId,$member->member_id,'once_card',$member_once_card_item_id,$num,$remain_num,$remark,2,$this->request->accountId);

            if(!$res){

                Db::rollback();

                return $this->error('核销失败');

            }



            //打印机

            $printer_logic =new PrinterLogic($this->request->shopId);

            $printer_logic->print('onceCardOrderWriteOff',$res);

            Db::commit();

            return $this->success('核销成功');

        }catch (\Exception $e){

            Db::rollback();

            return $this->error($e->getMessage());

        }

    }



    public function getMemberOnceCardLogs()

    {

        $member_id=$this->request->param('member_id/d',0);

        $type=$this->request->param('type/d',1);

        if(!in_array($type,[1,2])) $type=1;

        switch ($type){

            case 1:

                $return=$this->getWriteOffLogs($member_id);

                break;

            case 2:

                $return=$this->getApplyLogs($member_id);

                break;

        }



        return $this->success($return);

    }







    protected function getWriteOffLogs($member_id)

    {

        $where=[

            ['shop_id','=',$this->request->shopId],

            ['member_id','=',$member_id],

            ['source','=','once_card'],

        ];

        $project_write_off_model = new ProjectWriteOffModel();

        $project_write_off_model=$project_write_off_model->with(['once_card'=>function($query){

            $query->field('member_once_card_id,name');

        }]);

        $order=['add_time'=>'desc'];

        $field="*";

        $append=['add_time_format'];

        $return=DataLogic::getDataList($project_write_off_model,$where,$order,$field,$this->request->limit,$this->request->page,$append);

        return $return;

    }



    protected function getApplyLogs($member_id)

    {

        $where=[

            ['shop_id','=',$this->request->shopId],

            ['member_id','=',$member_id],

            ['source','=','once_card'],

        ];

        $apply_logs_model = new ApplyLogsModel();

        $order=['add_time'=>'desc'];

        $field="*";

        $append=['add_time_format'];

        $return=DataLogic::getDataList($apply_logs_model,$where,$order,$field,$this->request->limit,$this->request->page,$append);

        return $return;

    }

}

